﻿CREATE PROCEDURE [dbo].[proc_Loan_HK]
	(
		@id INT	
	)
AS
BEGIN
	
BEGIN TRANSACTION--开始事务
DECLARE @errorSun INT --定义错误计数器
SET @errorSun=0 --没错为0
	
	DECLARE @f INT
	SELECT @f=flag FROM Loan l WHERE id=@id
	
	IF @f=1
	BEGIN
		RETURN
	END
	
	UPDATE Loan
	SET
		flag = 1,HKDate = GETDATE() WHERE id=@id
		

if @@ROWCOUNT<1
		begin
			set @errorSun=@errorSun+1		
			goto e;
		end

INSERT INTO [Finance_RunningAccount]
           (
           [CreateDate]
           ,[TradeDate]
           ,[Summary]
           ,[AccountsTypeId]
           ,[AccountsTypeName]
           ,[ParentId]
           ,[ParentName]
           ,[SubjectId]
           ,[SubjectName]
           ,[PaymentTypeId]
           ,[PaymentTypeName]
           ,[BankId]
           ,[BankName]
           ,[Income]
           ,[Outlay]
           ,[Agent]
           ,[AgentName]
           ,[UserName]
           ,[EName]
           ,[CompanyId]
           ,[Description]
           ,[BillNumber]
           ,[OrderId]
           ,[Renling]
           ,[IOTypeId]
           ,[isGreen],l_id)
     SELECT 
           
           GETDATE()
           ,CONVERT(VARCHAR(10),GETDATE(),120)
           ,'[借款收入]'+l.Summary
           ,1
           ,'收入'
           ,0
           ,''
           ,0
           ,''
           ,[PaymentTypeId]
           ,[PaymentTypeName]
           ,[BankId]
           ,[BankName]
           ,l.[Money]
           ,0
           ,l.ENameId
           ,l.EName
           ,l.userid
           ,l.username
           ,l.CompanyId
           ,l.Cause
           ,''
           ,''
           ,2
           ,0
           ,0,@id
     FROM Loan l WHERE  l.id=@id
           
if @@ROWCOUNT<1
	begin
		set @errorSun=@errorSun+1		
		goto e;
    end

e:
    PRINT @errorSun
	if @errorSun>0
	begin
		rollback TRANSACTION
	
	end
	else
	begin
		commit TRANSACTION
	END
end		
	RETURN
